package com.opennews.openplatform.myspringbootmvccore.extension

import com.fasterxml.jackson.databind.ObjectMapper
import jakarta.servlet.http.HttpServletResponse
import org.springframework.http.HttpHeaders
import java.time.Instant

/**
 * Sends http error to client as request response.
 * Example:
 * {
 * success: false,
 * timestamp: 1642586379,
 * status: 401,
 * error: "UNAUTHORIZED",
 * message: "ERROR_USER_ACCOUNT_NOT_AUTHORIZED",
 * path: "/family-expense/api/user"
 * }
 *
 * @param response:   Http response.
 * @param httpStatus: Http status.
 * @param error:      String to identify error.
 * @param message:    String of more specific message.
 * @param path:       String of request url path.
 */
fun HttpServletResponse.sendErrorResponse(
    httpStatus: Int,
    error: String,
    message: String,
    path: String,
) {
    this.resetBuffer()
    this.status = httpStatus
    this.addHeader("X-Error-Message", message)
    this.setHeader(HttpHeaders.CONTENT_TYPE, "application/json")

    val errorResponse = mapOf(
        "success" to false,
        "timestamp" to Instant.now().epochSecond,
        "status" to httpStatus,
        "error" to error,
        "message" to message,
        "path" to path
    )

    try {
        val jsonResponse = ObjectMapper().writeValueAsString(errorResponse)
        this.outputStream.print(jsonResponse)
        this.flushBuffer()
    } catch (e: Exception) {
        throw RuntimeException(e)
    }
}